import { reqGetAllChannels } from '@/api/channel'
const state = {
  // 我的频道
  channels: [],
  // 所有的频道数据
  allChannels: []
}
const mutations = {
  setChannels (state, channels) {
    state.channels = channels
  },
  setAllChannels (state, allChannels) {
    state.allChannels = allChannels
  },
  addMyChannel (state, channel) {
    state.channels.push(channel)
  },
  delChannel (state, index) {
    state.channels.splice(index, 1)
  }
}
const actions = {
  async getAllChannelsAsync (context) {
    const res = await reqGetAllChannels()
    context.commit('setAllChannels', res.data.data.channels)
  }
}
const getters = {
  // 方式一
  // optionalChannels (state) {
  //   return state.allChannels.filter(item => {
  //     let flag = true
  //     state.channels.forEach(channels => {
  //       if (item.id === channels.id) {
  //         flag = false
  //       }
  //     })
  //     return flag
  //   })
  // }
  // 方式二
  // 过滤所有频道 筛选可选频道  判断所有频道项的id是否有我的频道的id
  // optionalChannels: (state) => {
  //   // 对 allChannels 中的元素进行过滤, 只保留那些没有在 channels 中出现的元素
  //   const results = state.allChannels.filter(channel => {
  //     const index = state.channels.findIndex(item => item.id === channel.id)
  //     // 如果找到了, index不是 -1, 如果找不到才是 -1 (要留下)
  //     return index === -1
  //   })
  //   return results
  // }
  // 简写
  optionalChannels: (state) => state.allChannels.filter(channel => state.channels.findIndex(item => item.id === channel.id) === -1)

}

export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}
